package com.xsf.jieyou.business.controller;

import com.xsf.jieyou.business.common.dto.ResponseResult;
import com.xsf.jieyou.business.feign.dto.params.ProfileParam;
import com.xsf.jieyou.provider.api.ProviderTbUserService;
import com.xsf.jieyou.provider.domain.TbUser;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户个人信息管理 启动类。
 *
 * @author xsf
 * @version v1.0.0
 * @date 2019/11/15 0015 16:29
 * @see com.xsf.jieyou.business.controller
 **/
@RestController
@RequestMapping("profile")
public class ProfileController {
    @Reference(version = "1.0.0")
    private ProviderTbUserService providerTbUserService;

    /**
     * 获取个人信息
     *
     * @return {@link ResponseResult}
     */
    @GetMapping(value = "info")
    public ResponseResult<?> info() {
        // 1、获取认证用户名
        String username = this.getAuthenticationName();

        // 2、获取用户对象
        TbUser tbUser = this.providerTbUserService.get(username);

        // 3、封装
        ProfileParam profileParam = new ProfileParam();
        BeanUtils.copyProperties(tbUser, profileParam);

        return ResponseResult.ok(profileParam);
    }

    /**
     * 获取 oAuth2 认证用户名
     *
     * @return 认证用户名
     */
    private String getAuthenticationName() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // "#"是无密码方式登录标记
        return authentication.getName().startsWith("#") ?
                authentication.getName().substring(1) :
                authentication.getName();
    }

}
